#!/bin/bash
set -e

if [ $# -eq 0 ]; then
    echo "Using $0 [-s device_id] [root] [-r] src_file_path target_path"
    exit
fi

device_id=""
file_path=""
target_path=""
reboot_flag=0
root_flag=0

PAMCOUNT=$#

# 把参数按顺序存入数组
i=1
while [ $i -le $PAMCOUNT ]
do
    args[$i]=$1
    ((i++))
    # 将参数向前移动,使 $1 变成 $2
    shift
done

i=1
while [ $i -le $PAMCOUNT ]
do
    param=${args[$i]}
    if [ "-s" = "$param" ]; then
	((i++))
	device_id="${args[$i]}"
    elif [ "-r" = "$param" ]; then
	reboot_flag=1
    elif [ "root" = "$param" ]; then
        root_flag=1
    elif [ ! -e "$param" ]; then
	echo "ERROR: $param : No such file or directory"
	exit
    else
	((i++))
	file_path="$param"
	target_path="${args[$i]}"
    fi
    ((i++))
done

# echo "[DEBUG] device_id="$device_id", file_path="$file_path", target_path="$target_path", reboot_flag="$reboot_flag
if [ -z "$file_path" ]; then
    echo "ERROR: src file is null."
    exit
fi
if [ -z "$target_path" ]; then
    echo "ERROR: target path is null."
fi

function append_device_id(){
    if [ -n "$device_id" ]; then
	cmd="$cmd -s $device_id"
    fi
}

#adb root
if [ 1 -eq $root_flag ]; then
    cmd="adb"
    append_device_id
    cmd="$cmd root"
    echo "$cmd"
    eval "$cmd"
fi

# adb remount
cmd="adb"
append_device_id
cmd="$cmd remount"
echo "$cmd"
eval "$cmd"

# adb push
cmd="adb"
append_device_id
# If it's a directory, first remove the directory in board.
if [ -d ${file_path} ]; then
    # Find last paragraph name in the path.
    last_src="${file_path##*/}"
    last_desc="${target_path##*/}"
    dir_remove="${target_path}"
    if [ "${last_src}" != "${last_desc}" ]; then
        # Find separator in last char.
        LAST_INDEX=${#target_path}
	((LAST_INDEX=LAST_INDEX-1))
	LAST_CHAR="${target_path:${LAST_INDEX}}"
	SEPARATOR="/"
	if [ '/' == ${LAST_CHAR} ]; then
	    SEPARATOR=""
	fi
        dir_remove="${target_path}${SEPARATOR}${last_src}"
    fi
    sub_cmd="${cmd} shell rm -rf ${dir_remove}"
    echo "${sub_cmd}"
    eval "${sub_cmd}"
    unset sub_cmd
fi
cmd="$cmd push $file_path $target_path"
echo "$cmd"
eval "$cmd"

#adb shell sync
cmd="adb"
append_device_id
cmd="$cmd shell sync"
echo "$cmd"
eval "$cmd"

#adb reboot
if [ 1 -eq $reboot_flag ]; then
    cmd="adb"
    append_device_id
    cmd="$cmd reboot"
    echo "$cmd"
    eval "$cmd"
fi

